import Layer from '../core/Layer';
import Point from '../core/Point';
import Color from '../core/Color';
import MultiLine from '../base/MultiLine';
import Circle from '../base/Circle';
import Event from '../event/Event';


export default class extends Layer {
    constructor(canvas, option) {
        super(canvas);
        this.width = option.width;
        this.height = option.height;
        this.line = option.line || [];
        this.index = option.index || this.line.length;
        this.color = option.color || '#333333';
        this.touchCallback = option.touchCallback;
    }

    make() {
        this.childs.splice(0, this.childs.length);
        if (this.line.length === 0) {
            return;
        }
        let max = this.line[0].value;
        let min = this.line[0].value;
        for (let i = 0; i < this.line.length; i++) {
            if (this.line[i].value > max) {
                max = this.line[i].value;
            }
            if (this.line[i].value < min) {
                min = this.line[i].value;
            }
        }
        this.xStep = this.width / (this.line.length + 1);
        this.yStep = this.height / (max - min);
        let points = [];
        for (let i = 0; i < this.index; i++) {
            const point = new Point(this.position.x + i * this.xStep, this.position.y + (this.line[i].value - min) * this.yStep);
            points.push(
              point
            );
            let circle = new Circle(this.canvas, 4);
            circle.setPosition(point);
            circle.setColor(new Color(this.color));
            this.addChild(circle);
        }
        let multiLine = new MultiLine(this.canvas, points);
        multiLine.setLineWidth(2);
        multiLine.setColor(new Color(this.color));
        this.addChild(multiLine);
        this.addEventListener(Event.EVENT_TOUCH_START, (e) => {
            let { eventPoint } = e;
            const box = this.canvas.canvas.getBoundingClientRect();
            const index = Math.round(eventPoint.x / this.xStep);
            const eventX = index * this.xStep * box.width / this.canvas.width + box.left;
            const eventY = eventPoint.y * box.height / this.canvas.height + box.top;
            this.touchCallback && this.touchCallback(this.line[index], { x: eventX, y: eventY });
        });
    }
    /**
     * 点击检测
     * @param point
     * @returns {boolean}
     */
    containsPoint(point) {
        return point.x <= this.position.x + this.width
            && point.x >= this.position.x
            && point.y >= this.position.y
            && point.y <= this.position.y + this.height;
    }
}
